import axios from 'axios';

// const URLTYPE = 'application/x-www-form-urlencoded';
// const JSONTYPE = 'application/json';
// const MULTITYPE = 'multipart/form-datan';

class FetchUtil {
  static baseFetch = async (url, options={ method: 'GET' }) => {
    const { method, ...rest } = options;
    const requestConfig = {
      method,
      url,
      ...rest,
    };

    try {
      console.log(`【请求参数】${url}--options------->`, options);
      const response = await axios(requestConfig);
      // 处理response
      const { status } = response;
      console.log(`【请求结果】${url}--status------->`, status);
      console.log(`【请求结果】${url}--response------->`, response.data);
      if (status === 200) {
        if (!response.data.code) {
          response.data.code = 0;
        }
        return response.data;
      } if (status === 413) {
        return {
          code: -999,
          message: '上传文件太大'
        };
      } if (status === 401) {
        // 需要刷新token
        return {
          code: -998,
          message: '授权令牌过期'
        };
      }
      return {
        code: -997,
        message: '请求异常'
      };
    } catch (error) {
      const { status, statusText } = error.response;
      console.log(`【请求异常】${url}--error--status----->`, status);
      console.log(`【请求异常】${url}--error--statusText----->`, statusText);

      throw error;

      // return {
      //   code: -996,
      //   message: statusText,
      // };
    }
  }

  static refreshToken = async () => {
    console.log('refreshToken');
  }

  /**
   * 不需要token 的请求
   * url: api
   * options:
   */
  static fetchNoToken = async (url, options) => {
    const result = await FetchUtil.baseFetch(url, options);
    return result;
  }

  /**
   * x需要token 的请求
   * url: api
   * options:
   */
  static fetchByToKen = async (url, options) => {
    const result = await FetchUtil.baseFetch(url, options);
    return result;
  }

  static upload = async () => {

  }

  static socket = async () => {

  }
}

export default FetchUtil;
